package com.itheima.servlet;

import com.itheima.bean.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/AddStudentServlet")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //获取所有请求参数
            Map<String, String[]> map = request.getParameterMap();
            // 封装数据
            Student stu = new Student();
            BeanUtils.populate(stu,map);
            //将学生对象的数据保存到d:/stu.txt文件中
            BufferedWriter bw = new BufferedWriter(new FileWriter("d:/stu.txt",true));
            bw.write(stu.getUsername() + "," + stu.getAge()+ "," + stu.getScore());
            bw.newLine();
            bw.close();
            //重定向到查询servlet
            response.sendRedirect(request.getContextPath() + "/ListStudentServlet");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
